package com.xiangyun.auth.config;

import java.security.KeyPair;
import java.util.Arrays;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import com.xiangyun.auth.utils.RSAUtils;

@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
public class HtAuthAuthorizationServiceConfiguration extends AuthorizationServerConfigurerAdapter{

	private static final String JWTPRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJD/YAX9k1/+rhskToZE7/599LJCUtJmM8qj6uNRd4Qh7l5R+RvbLFFl9ndXQT41K1pTlTNVAuyI3CtRdfY0lytW13ZG64AZCjxcAx3uUeIvAJc54toAjfNznABMj5FAXr/M143fAfvhB2smOLxyY7is4mUzPsGVMZA9CSpLCqOXAgMBAAECgYEAisj1FybMzkBOU8pfouMPN+9FrO4QqjSK9DYLWMOcewujRgJ+Rux1MgA/daE94JYxxcZk8/o1z0N8QbY6C4vw+Gha/yvCqbF7bvo5KOFaGLEnyPvsqYEvLFSoi/VuE060x+2VIqmdyYWIGw9KTkYB53pGrL4W2WJTDoWduVCFyPECQQDKy1CmtUF8W6+GFO9Inr791I+oKUTxo++I86VICPLPa8tbae+tc2uPMQ8nmiXr4SmbdlVAIndUZuXY3xZAk3rJAkEAtwolJjrmMhBgAsbGc7P0GIQ1S2Kss0zNmDFCiRtQHEiFAz9xqHsYujUimvV1fPKHUDZlflId/DpwHHWZLQX7XwJANuy2HVC+OcZDVddZr5t/MxRdDDiRObki6T7EJyx1RwR1AX9BsQKvwQqShjFTz/0d3cNA96veEfgEjKZvSnInMQJBAJEM4hmkrU1ZOqyYlyWToslW4+EEpjVElNyZlM+QLHDtazMCsPBB9HuDphPElsFYdLC1GsL7EjYSnUuASc2rIuMCQQCov6OfTONon7yRH9B0OMbImCcFNu+ivxqwUnZIONPKsSgivdpU2NqsZaYpUvOIkpPu3a/9LuPJSCarFlS7sv1y";

	private static final String JWTPUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQ/2AF/ZNf/q4bJE6GRO/+ffSyQlLSZjPKo+rjUXeEIe5eUfkb2yxRZfZ3V0E+NStaU5UzVQLsiNwrUXX2NJcrVtd2RuuAGQo8XAMd7lHiLwCXOeLaAI3zc5wATI+RQF6/zNeN3wH74QdrJji8cmO4rOJlMz7BlTGQPQkqSwqjlwIDAQAB";

	//配置数据源
	@Autowired
	private DataSource dataSource;
	
	/**
	 * 认证服务器中token令牌的存储方式，目前采用主流的jwt方式保存
	 * 验证方法采用网关验证，然后转发明文的方式进行资源服务器访问
	 * @return
	 */
	@Bean
	public TokenStore tokenStore() {
		return new JwtTokenStore(tokenConverter());
	}

	/**
	 * jwt令牌增强器具体作用不知道……
	 * @return
	 */
	public JwtAccessTokenConverter tokenConverter() {
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		KeyPair keyPair = null;
		try {
			keyPair = new KeyPair(RSAUtils.getPublicKey(JWTPUBLIC_KEY), RSAUtils.getPrivateKey(JWTPRIVATE_KEY));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		converter.setKeyPair(keyPair);
		return converter;
	}
	
	/**
	 * 客户端详情(目前用jdbc保存到数据库当中)
	 * @return
	 */
	@Bean
	public ClientDetailsService clientDetailsService() {
		return new JdbcClientDetailsService(dataSource);
	}
	
	/**.
	 * 令牌服务包括了客户端详情、令牌增强器、是否支持刷新令牌以及令牌有效期
	 * @return
	 */
	@Bean
	public AuthorizationServerTokenServices tokenService() {
		DefaultTokenServices services = new DefaultTokenServices();
		services.setClientDetailsService(clientDetailsService());
		services.setTokenStore(tokenStore());
		
		TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenConverter()));
		services.setTokenEnhancer(tokenEnhancerChain);
		
		return services;
	}
	
	@Bean
	public AuthorizationCodeServices authorizationCodeServices() {
		return new JdbcAuthorizationCodeServices(dataSource);
	}

	/**
	 * 重写了令牌端点服务
	 */
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		// TODO Auto-generated method stub
		endpoints.tokenServices(tokenService())
		.authorizationCodeServices(authorizationCodeServices());
	}

	/**
	 * 重新配置客户端详情服务
	 */
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		// TODO Auto-generated method stub
		clients.withClientDetails(clientDetailsService());
	}
	
	
	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		// TODO Auto-generated method stub
		security.tokenKeyAccess("permitAll()")
		.checkTokenAccess("permitAll()");	
	}
}
